package com.enjoychain.www.security.service.impl.task;

import com.enjoychain.www.security.entity.*;
import com.enjoychain.www.security.pojo.EnvTaskDetail;
import com.enjoychain.www.security.pojo.TaskPojo;
import com.enjoychain.www.security.service.*;
import com.enjoychain.www.security.util.DeepCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskEnvServiceImpl implements ITaskEnvService {


    @Autowired
    ITaskDetailItemService itemService;

    @Autowired
    IJobInfoService jobInfoService;

    @Autowired
    ICorpBasicInfoService basicInfoService;

    @Autowired
    ITaskEquipItemService taskEquipItemService;

    @Autowired
    IXcBasicService basicService;

    @Autowired
    ITaskCorpEnvBasicInfoService taskCorpEnvBasicInfoService;

    @Autowired
    ICorpEnvBasicInfoService envBasicInfoService;

    @Autowired
    ITaskProductProcessService productProcessService;

    @Autowired
    ITaskMergencyInfoService mergencyInfoService;

    @Autowired
    ITaskWasteWaterService wasteWaterService;

    @Autowired
    ITaskRainSewageService rainSewageService;

    @Autowired
    ITaskNoiseService noiseService;

    @Autowired
    ITaskSolidWasteService solidWasteService;

    @Autowired
    ITaskHwStoreStatusService hwStoreStatusService;

    @Autowired
    ITaskHwDataService hwDataService;

    @Autowired
    ITaskDetailOtherService taskOtherService;

    @Autowired
    ITaskProductSectionItemService productSectionItemService;

    @Autowired
    ITaskGasPollutionItemService gasPollutionItemService;


    ////// task basic info
    @Autowired
    ITaskEpHwItemService epHwItemService;

    @Autowired
    ITaskEpEiaService epEiaService;

    @Autowired
    ITaskEpEquipInfoService epEquipInfoService;

    @Autowired
    ITaskEpGasEquipmentService epGasEquipmentService;

    @Autowired
    ITaskEpSolidWasteItemService epSolidWasteItemService;

    @Autowired
    IBasicFileService fileService;





    @Override
    public void buildEnvTask(CorpBasicInfo basicInfo, String taskId) {
        //3、构建企业基础信息
        CorpEnvBasicInfo corpEnvBasicInfo = envBasicInfoService.getById(basicInfo.getId());
        if (corpEnvBasicInfo == null) {
            envBasicInfoService.inital(basicInfo);
        }
        TaskCorpEnvBasicInfo envBasicInfo = TaskEnvConverts.convertEnvBasicInfoToTaskBasicInfo(envBasicInfoService.getDetailById(basicInfo.getId()), taskId);
        saveTaskDetail(buildSingleTaskDetail(taskId), taskId, envBasicInfo);
        saveBasicInfo(envBasicInfo);
    }

    @Override
    public TaskCorpEnvBasicInfo getCorpEnvBasicInfoByTaskId(String taskId) {
        return taskCorpEnvBasicInfoService.getDetailByTaskId(taskId);
    }

    @Override
    public EnvTaskDetail getEnvTaskDetailByTaskId(String taskId) {
        EnvTaskDetail taskDetailNew = new EnvTaskDetail();
        taskDetailNew.setEquipItems(taskEquipItemService.listByTaskId(taskId));
        taskDetailNew.setProductProcessInfo(productProcessService.getByTaskId(taskId));
        TaskDetailOther other = taskOtherService.getByTaskId(taskId);
        taskDetailNew.setOwnerMonitorStatus(other.getOwnerMonitorStatus());
        taskDetailNew.setPlanPublishStatus(other.getPlanPublishStatus());
        taskDetailNew.setMergencyInfo(mergencyInfoService.getByTaskId(taskId));
        taskDetailNew.setWasteWaterInfo(wasteWaterService.getByTaskId(taskId));
        taskDetailNew.setRainSewageInfo(rainSewageService.getDetailByTaskId(taskId));
        taskDetailNew.setGasPollutionItems(gasPollutionItemService.listByTaskId(taskId));
        taskDetailNew.setGasSectionItems(productSectionItemService.listByTaskId(taskId));
        taskDetailNew.setTaskNoiseInfo(noiseService.getByTaskId(taskId));
        taskDetailNew.setSolidWasteInfo(solidWasteService.getDetailByTaskId(taskId));
        taskDetailNew.setHwStoreStatusInfos(hwStoreStatusService.listByTaskId(taskId));
        taskDetailNew.setHwData(hwDataService.getByTaskId(taskId));
        return taskDetailNew;
    }

    @Override
    public void removeByTaskId(String taskId) {
        this.removeEnvCorpByTaskId(taskId);
        this.removeEnvDetail(taskId);
    }

    @Override
    public void saveEnvCorpBasicInfo(TaskPojo taskPojo) {
        this.saveBasicInfo(taskPojo.getEnvCorpInfo() == null ? taskPojo.getCorpInfo():taskPojo.getEnvCorpInfo());
    }

    @Override
    public void saveEnvTaskDetail(TaskPojo taskPojo) {
        this.saveTaskDetail(taskPojo.getEnvTaskDetail(),taskPojo.getId(),taskPojo.getEnvCorpInfo());
    }


    private void saveTaskDetail(EnvTaskDetail detail, String taskId, TaskCorpEnvBasicInfo basicInfo) {
        // 设备情况
        handleEquipItems(detail, taskId, basicInfo);

        productProcessService.saveOrUpdate(detail.getProductProcessInfo());

        TaskDetailOther other = taskOtherService.getByTaskId(taskId);
        other.setPlanPublishStatus(detail.getPlanPublishStatus());
        other.setOwnerMonitorStatus(detail.getOwnerMonitorStatus());
        taskOtherService.saveOrUpdate(other);

        mergencyInfoService.saveOrUpdate(detail.getMergencyInfo());
        wasteWaterService.saveOrUpdate(detail.getWasteWaterInfo());
        rainSewageService.saveOrUpdate(detail.getRainSewageInfo());

        // 废气工段信息
        handleGasSections(detail, taskId, basicInfo);

        noiseService.saveOrUpdate(detail.getTaskNoiseInfo());

        // 如果一般固废标志张贴了，不需要图片。
        if (detail.getTaskNoiseInfo() != null && detail.getSolidWasteInfo().getSolidWasteNoteStatus() != null) {
            if (detail.getSolidWasteInfo().getSolidWasteNoteStatus().equals("是")) {
                fileService.removeBatchByIds(detail.getSolidWasteInfo().getFiles());
            }
        }
        solidWasteService.saveOrUpdate(detail.getSolidWasteInfo());
        hwStoreStatusService.saveOrUpdateBatch(detail.getHwStoreStatusInfos());
        hwDataService.saveOrUpdate(detail.getHwData());
    }


    private void handleGasSections(EnvTaskDetail detail, String taskId, TaskCorpEnvBasicInfo basicInfo) {
        //1、先更新数据
        // 如果是'能有效收集'的，不需要上传照片
        if (detail.getGasPollutionItems() != null) {
            for (TaskProductSectionItem item : detail.getGasSectionItems()) {
                if (StringUtils.isNotEmpty(item.getStatus()) && item.getStatus().equals("能有效收集")) {
                    fileService.removeBatchByIds(item.getFiles());
                }
            }
        }
        productSectionItemService.saveOrUpdateBatch(detail.getGasSectionItems());


        gasPollutionItemService.saveOrUpdateBatch(detail.getGasPollutionItems());

        List<TaskEpGasEquipment> gasEquipmentItems = basicInfo.getGasEquipmentItems();
        List<TaskProductSectionItem> oldSectionItems = productSectionItemService.listByTaskId(taskId);

        List<TaskGasPollutionItem> oldGasPollutionItems = gasPollutionItemService.listByTaskId(taskId);
        List<TaskGasPollutionItem> backUpOldGasPollutionItems = DeepCopyUtil.getInstance().deepCopy(oldGasPollutionItems);

        Set<String> sectionSet = new HashSet<>();

        for (TaskEpGasEquipment epGasEquipment : gasEquipmentItems) {
            if (StringUtils.isNotEmpty(epGasEquipment.getDischargeStatus()) && epGasEquipment.getDischargeStatus().equals("有组织排放")) {
                boolean flag = true;
                for (TaskGasPollutionItem taskEquipItem : backUpOldGasPollutionItems) {
                    log.info("taskEquipItem:" + taskEquipItem.toString() + "; epGasEquipment: " + epGasEquipment.toString());
                    if (taskEquipItem != null && epGasEquipment != null && epGasEquipment.getPollutionFactor() != null && taskEquipItem.getPollutionFactor() != null && epGasEquipment.getPollutionFactor().equals(taskEquipItem.getPollutionFactor())
                            && epGasEquipment.getExhaustFunnelNo().equals(taskEquipItem.getExhaustFunnelNo())
                            && epGasEquipment.getProductSection().equals(taskEquipItem.getProductSection())) {
                        flag = false;
                        oldGasPollutionItems.removeIf(a -> a.getId().equals(taskEquipItem.getId()));
                    }
                }
                if (flag) {
                    // 新增
                    gasPollutionItemService.initial(epGasEquipment, taskId);
                }
                sectionSet.add(epGasEquipment.getProductSection());
            }
        }
        gasPollutionItemService.removeBatchByIds(oldGasPollutionItems);

        for (TaskProductSectionItem item : oldSectionItems) {
            if (!sectionSet.contains(item.getProductSection())) {
                productSectionItemService.removeById(item);
            } else {
                sectionSet.remove(item.getProductSection());
            }
        }
        for (String section : sectionSet) {
            TaskProductSectionItem item = new TaskProductSectionItem();
            item.setTaskId(taskId);
            item.setProductSection(section);
            productSectionItemService.save(item);
        }
    }

    void handleEquipItems(EnvTaskDetail detail, String taskId, TaskCorpEnvBasicInfo basicInfo) {
        //1、先更新
        taskEquipItemService.saveOrUpdateBatch(detail.getEquipItems());
        //2、按照基础信息处理
        List<TaskEpEquipInfo> equipInfos = basicInfo.getEquipItems();
        List<TaskEquipItem> oldEquipItems = taskEquipItemService.listByTaskId(taskId);
        List<TaskEquipItem> backUpOldEquipItems = DeepCopyUtil.getInstance().deepCopy(oldEquipItems);
        for (TaskEpEquipInfo epEquipInfo : equipInfos) {
            boolean flag = true;
            for (TaskEquipItem taskEquipItem : backUpOldEquipItems) {
                if (epEquipInfo.getEquipName().equals(taskEquipItem.getEquipName())) {
                    flag = false;
                    oldEquipItems.removeIf(a -> a.getId().equals(taskEquipItem.getId()));
                }
            }
            if (flag) {
                // 新增
                TaskEquipItem equipItem = new TaskEquipItem();
                equipItem.setEquipName(epEquipInfo.getEquipName());
                equipItem.setTaskId(taskId);
                equipItem.setEquipHisNum(epEquipInfo.getEquipNum());
                taskEquipItemService.save(equipItem);
            }
        }
        taskEquipItemService.removeBatchByIds(oldEquipItems);

    }

    EnvTaskDetail getTaskDetailByTaskId(String taskId) {
        EnvTaskDetail envTaskDetail = new EnvTaskDetail();
        envTaskDetail.setEquipItems(taskEquipItemService.listByTaskId(taskId));
        envTaskDetail.setProductProcessInfo(productProcessService.getByTaskId(taskId));
        TaskDetailOther other = taskOtherService.getByTaskId(taskId);
        envTaskDetail.setOwnerMonitorStatus(other.getOwnerMonitorStatus());
        envTaskDetail.setPlanPublishStatus(other.getPlanPublishStatus());
        envTaskDetail.setMergencyInfo(mergencyInfoService.getByTaskId(taskId));
        envTaskDetail.setWasteWaterInfo(wasteWaterService.getByTaskId(taskId));
        envTaskDetail.setRainSewageInfo(rainSewageService.getDetailByTaskId(taskId));
        envTaskDetail.setGasPollutionItems(gasPollutionItemService.listByTaskId(taskId));
        envTaskDetail.setGasSectionItems(productSectionItemService.listByTaskId(taskId));
        envTaskDetail.setTaskNoiseInfo(noiseService.getByTaskId(taskId));
        envTaskDetail.setSolidWasteInfo(solidWasteService.getDetailByTaskId(taskId));
        envTaskDetail.setHwStoreStatusInfos(hwStoreStatusService.listByTaskId(taskId));
        envTaskDetail.setHwData(hwDataService.getByTaskId(taskId));
        return envTaskDetail;
    }


    void removeEnvDetail(String taskId) {
        taskEquipItemService.removeAllByTaskId(taskId);
        productProcessService.removeByTaskId(taskId);
        taskOtherService.removeByTaskId(taskId);
        mergencyInfoService.removeByTaskId(taskId);
        wasteWaterService.removeByTaskId(taskId);
        rainSewageService.removeDetailByTaskId(taskId);
        gasPollutionItemService.removeDetailByTaskId(taskId);
        productSectionItemService.removeDetailByTaskId(taskId);
        noiseService.removeByTaskId(taskId);
        solidWasteService.removeDetailByTaskId(taskId);
        hwStoreStatusService.removeDetailByTaskId(taskId);
        hwDataService.removeByTaskId(taskId);
    }


    /**
     * 构建新任务
     *
     * @param taskId 任务id
     * @return
     */
    private EnvTaskDetail buildSingleTaskDetail(String taskId) {
        EnvTaskDetail taskDetail = new EnvTaskDetail();

        TaskProductProcess productProcess = new TaskProductProcess();
        productProcess.setTaskId(taskId);
        productProcessService.save(productProcess);
        taskDetail.setProductProcessInfo(productProcess);

        TaskMergencyInfo mergencyInfo = new TaskMergencyInfo();
        mergencyInfo.setTaskId(taskId);
        mergencyInfoService.save(mergencyInfo);
        taskDetail.setMergencyInfo(mergencyInfo);

        TaskWasteWater wasteWater = new TaskWasteWater();
        wasteWater.setTaskId(taskId);
        wasteWaterService.save(wasteWater);
        taskDetail.setWasteWaterInfo(wasteWater);

        TaskRainSewage rainSewage = new TaskRainSewage();
        rainSewage.setTaskId(taskId);
        rainSewageService.save(rainSewage);
        taskDetail.setRainSewageInfo(rainSewage);

        TaskNoise noise = new TaskNoise();
        noise.setTaskId(taskId);
        noiseService.save(noise);
        taskDetail.setTaskNoiseInfo(noise);

        TaskSolidWaste solidWaste = new TaskSolidWaste();
        solidWaste.setTaskId(taskId);
        solidWasteService.save(solidWaste);
        taskDetail.setSolidWasteInfo(solidWaste);

        taskDetail.setHwStoreStatusInfos(hwStoreStatusService.initial(taskId));

        TaskHwData hwData = new TaskHwData();
        hwData.setTaskId(taskId);
        hwDataService.save(hwData);
        taskDetail.setHwData(hwData);

        TaskDetailOther taskOther = new TaskDetailOther();
        taskOther.setTaskId(taskId);
        taskOtherService.save(taskOther);

        return taskDetail;
    }


    private void saveBasicInfo(TaskCorpEnvBasicInfo corpInfo) {
        taskCorpEnvBasicInfoService.saveOrUpdate(corpInfo);

        epEiaService.removeByTaskId(corpInfo.getTaskId());
        if (corpInfo.getReportItems() != null && corpInfo.getReportItems().size() > 0) {
            for (TaskEpEia report : corpInfo.getReportItems()) {
                if (StringUtils.isEmpty(report.getTaskId())) {
                    report.setTaskId(corpInfo.getTaskId());
                }
                if (StringUtils.isEmpty(report.getCorpId())) {
                    report.setCorpId(corpInfo.getCorpId());
                }
            }
        }

        epEiaService.saveOrUpdateBatch(corpInfo.getReportItems());


        epEquipInfoService.removeByTaskId(corpInfo.getTaskId());
        if (corpInfo.getEquipItems() != null && corpInfo.getEquipItems().size() > 0) {
            for (TaskEpEquipInfo report : corpInfo.getEquipItems()) {
                if (StringUtils.isEmpty(report.getTaskId())) {
                    report.setTaskId(corpInfo.getTaskId());
                }
                if (StringUtils.isEmpty(report.getCorpId())) {
                    report.setCorpId(corpInfo.getCorpId());
                }
            }
        }
        epEquipInfoService.saveOrUpdateBatch(corpInfo.getEquipItems());


        epHwItemService.removeByTaskId(corpInfo.getTaskId());
        if (corpInfo.getHwItems() != null && corpInfo.getHwItems().size() > 0) {
            for (TaskEpHwItem report : corpInfo.getHwItems()) {
                if (StringUtils.isEmpty(report.getTaskId())) {
                    report.setTaskId(corpInfo.getTaskId());
                }
                if (StringUtils.isEmpty(report.getCorpId())) {
                    report.setCorpId(corpInfo.getCorpId());
                }
            }
        }
        epHwItemService.saveOrUpdateBatch(corpInfo.getHwItems());


        epGasEquipmentService.removeByTaskId(corpInfo.getTaskId());
        if (corpInfo.getGasEquipmentItems() != null && corpInfo.getGasEquipmentItems().size() > 0) {
            for (TaskEpGasEquipment report : corpInfo.getGasEquipmentItems()) {
                if (StringUtils.isEmpty(report.getTaskId())) {
                    report.setTaskId(corpInfo.getTaskId());
                }
                if (StringUtils.isEmpty(report.getCorpId())) {
                    report.setCorpId(corpInfo.getCorpId());
                }
            }
        }
        epGasEquipmentService.saveOrUpdateBatch(corpInfo.getGasEquipmentItems());


        epSolidWasteItemService.removeByTaskId(corpInfo.getTaskId());
        if (corpInfo.getSolidWasteItems() != null && corpInfo.getSolidWasteItems().size() > 0) {
            for (TaskEpSolidWasteItem report : corpInfo.getSolidWasteItems()) {
                if (StringUtils.isEmpty(report.getTaskId())) {
                    report.setTaskId(corpInfo.getTaskId());
                }
                if (StringUtils.isEmpty(report.getCorpId())) {
                    report.setCorpId(corpInfo.getCorpId());
                }
            }
        }
        epSolidWasteItemService.saveOrUpdateBatch(corpInfo.getSolidWasteItems());


    }

    private void removeEnvCorpByTaskId(String taskId) {
        taskCorpEnvBasicInfoService.removeByTaskId(taskId);
        epSolidWasteItemService.removeByTaskId(taskId);
        epEiaService.removeByTaskId(taskId);
        epGasEquipmentService.removeByTaskId(taskId);
        epEquipInfoService.removeByTaskId(taskId);
        epHwItemService.removeByTaskId(taskId);
    }
}
